package com.n9.excel;

import java.io.*;
import java.util.List;
import java.util.Objects;

/**
 * excel工具类
 * @author ice
 */
public final class ExcelUtils {

    /**
     * 读取excel数据
     * @param in
     * @param rowReader
     * @param <T>
     * @return
     */
    public static <T> List<T> readRows(InputStream in, ExcelRowReader<T> rowReader) {
        return readRows(in, rowReader, 1);
    }

    /**
     * 读取excel数据
     * @param in
     * @param rowReader
     * @param rowNum        数据行位置
     * @param <T>
     * @return
     */
    public static <T> List<T> readRows(InputStream in, ExcelRowReader<T> rowReader, int rowNum) {
        try {
            ExcelImport excelImport = new ExcelImport(in, rowNum, 0);
            return excelImport.getDataList(rowReader);
        } finally {
            close(in);
        }
    }


    /**
     * list数据写入到excel
     * @param headerNames
     * @param list
     * @param rowWriter
     * @param out
     * @param <T>
     */
    public static <T> void writeToExcel(List<String> headerNames, List<T> list, ExcelRowWriter<T> rowWriter, OutputStream out) {
        ExcelExport ee = new ExcelExport();
        ee.setHeader(headerNames);
        ee.setExportData(list, rowWriter);
        try {
            ee.write(out);
            out.flush();
            ee.dispose();
        } catch (IOException e) {
            throw new ExcelException("导出数据有误");
        } finally {
            close(out);
        }
    }

    /**
     * list数据写入到excel文件
     * @param headerNames
     * @param list
     * @param rowWriter
     * @param file
     * @param <T>
     */
    public static <T> void writeToExcel(List<String> headerNames, List<T> list, ExcelRowWriter<T> rowWriter, File file) {
        try {
            writeToExcel(headerNames, list, rowWriter, new FileOutputStream(file));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            throw new ExcelException("导出数据有误:" + e.getMessage());
        }
    }


    /**
     * 关闭流
     * @param closeable
     */
    private static void close(Closeable closeable) {
        if (Objects.nonNull(closeable)) {
            try {
                closeable.close();
            } catch (IOException e) {
                //ignore
            }
        }
    }

}
